function getPageTitleByQueryArray($queryStringArray){
    
    var $cat_parent_alias = $('#filter_form').attr('cat_parent_alias');
    var $queryArray = new Object();
    $.each($queryStringArray, function(index, value){
        $queryArray[value.split('=')[0]] = value.split('=')[1];             
    });

    if($queryArray.hasOwnProperty('dien-tich-su-dung') && $queryArray.hasOwnProperty('dien-tich-mat-bang')){
        var $areaUseIndex = $.inArray($queryArray['dien-tich-su-dung'], Object.keys($areaAboutData));
        var $areaFloorIndex = $.inArray($queryArray['dien-tich-mat-bang'], Object.keys($areaAboutData));
        if($areaUseIndex < $areaFloorIndex){
            delete $queryArray['dien-tich-mat-bang'];
        }
    }

    if($queryArray.hasOwnProperty('gia-tu') && $queryArray.hasOwnProperty('gia-den')){
        if(parseInt($queryArray['gia-den']) < parseInt($queryArray['gia-tu'])){
            delete $queryArray['gia-den'];
        }
    }      

    var $titleObject = new Object();
    $titleObject['catParentTitle'] = $catData[$cat_parent_alias]['name'];
    $titleObject['catTitle'] =  $queryArray.hasOwnProperty('child_alias') ? ' '+$catData[$cat_parent_alias]['cats'][$queryArray['child_alias']]['name'] : '';
    $titleObject['sortTitle'] = $queryArray.hasOwnProperty('sap-xep') ? ' '+$sortData[$queryArray['sap-xep']] : '';
    $titleObject['locationTitle'] = !$queryArray.hasOwnProperty('thanh-pho') ? ' toàn quốc' : (
        $queryArray.hasOwnProperty('quan') ? ' '+$cityData[$queryArray['thanh-pho']]['districts'][$queryArray['quan']]['name'] + ' - ' + $cityData[$queryArray['thanh-pho']]['name'] : ' '+$cityData[$queryArray['thanh-pho']]['name']
    );
    $titleObject['typeTitle'] = $queryArray.hasOwnProperty('loai-tin') ? ', loại tin: '+$typeData[$queryArray['loai-tin']] : '';
    $titleObject['stateTitle'] = $queryArray.hasOwnProperty('tinh-trang') ? ', tình trạng: '+$stateData[$queryArray['tinh-trang']] : '';

    $titleObject['priceTitle'] = '';
    if($queryArray.hasOwnProperty('gia-tu') && $queryArray.hasOwnProperty('gia-den') && $queryArray['gia-tu'] < $queryArray['gia-den']){
        $titleObject['priceTitle'] = ', giá từ ' + getPriceLabel($queryArray['gia-tu']) + ' đến ' + getPriceLabel($queryArray['gia-den']);
    }else if($queryArray.hasOwnProperty('gia-tu')){
        $titleObject['priceTitle'] = ', giá từ ' + getPriceLabel($queryArray['gia-tu']);
    }else if($queryArray.hasOwnProperty('gia-den')){
        $titleObject['priceTitle'] = ', giá tối đa ' + getPriceLabel($queryArray['gia-den']);
    }
    $titleObject['statusTitle'] = $queryArray.hasOwnProperty('trang-thai') ? ', trạng thái: '+$statusData[$queryArray['trang-thai']] : '';
    $titleObject['areaUseTitle'] = $queryArray.hasOwnProperty('dien-tich-su-dung') ? ', diện tích sử dụng: '+$areaAboutData[$queryArray['dien-tich-su-dung']] : '';
    $titleObject['areaFloorTitle'] = $queryArray.hasOwnProperty('dien-tich-mat-bang') ? ', diện tích mặt bằng: '+$areaAboutData[$queryArray['dien-tich-mat-bang']] : '';
    $titleObject['hasImageTitle'] = $queryArray.hasOwnProperty('co-anh') ? ', có ảnh' : '';
    $titleObject['isAllCityTitle'] = $queryArray.hasOwnProperty('toan-quoc') ? ', toàn quốc' : '';
    $titleObject['keywordTitle'] = $queryArray.hasOwnProperty('tim-kiem') ? ', từ khóa: ' + $queryArray['tim-kiem']  : '';

    $titleArray = [];
    $i = 0;
    $.each($titleObject, function($k, $v){
        if($.inArray($k, ['locationTitle', 'catParentTitle']) == -1){
            $titleArray[$i] = $v.toLowerCase();   
        }else{
            $titleArray[$i] = $v;
        }
        $i++;        
    });
    $title = $titleArray.join('');    
    return $title;
}


function ajaxFormPost(){

    var $areaUse = $('#dien-tich-su-dung').val();
    var $areaFloor = $('#dien-tich-mat-bang').val();
    if($areaUse != '' && $areaFloor != ''){
        var $areaUseIndex = $.inArray($areaUse, Object.keys($areaAboutData));
        var $areaFloorIndex = $.inArray($areaFloor, Object.keys($areaAboutData));
        if($areaUseIndex < $areaFloorIndex){
            myGrowl('Diện tích sử dụng không được nhỏ hơn diện tích mặt bằng.', 'error');
            $('#dien-tich-mat-bang').val('');
            return false;
        }
    }

    var $priceFrom = parseInt($('#gia-tu').val());
    var $priceTo = parseInt($('#gia-den').val());
    if($priceFrom != '' && $priceTo != ''){
        if($priceTo < $priceFrom){
            myGrowl('Giá đến phải lớn hơn giá từ.', 'error');
            $('#gia-den').val('');
            return false;
        }
    }

    //console.log($('#filter_form').serialize());
    //console.log($('#filter_form').serializeArray());
    var queryArray = [];
    var queryArrayUrl = [];
    var catChildAliasIndex = -1;;
    var index = 0;

    var querySearch = '';
    var catChildAlias = '';
    $.each($('#filter_form').serializeArray(), function(i, obj) {
        if(obj.value.trim() != '' && obj.value.trim() != '0'){
            if(obj['name'] == 'tim-kiem'){
                querySearch = obj['name'] +'='+ obj['value'];
                return true;   
            }
            if(obj['name'] == 'child_alias'){
                catChildAlias = '/'+ obj['value'];              
                catChildAliasIndex = index;              
            }

            queryArray[index] = obj['name'] +'='+ obj['value'];
            index++;    
        }
    });
    
    if(querySearch !== ''){
        queryArray[index++] = querySearch;    
    } 

    var queryArrayUrl = queryArrayUrl.concat(queryArray);
    if(catChildAliasIndex >= 0){
        queryArrayUrl.splice(catChildAliasIndex, 1);
    }

    var action = $('#filter_form').attr('action');
    var queryString = queryArrayUrl.join('&');
    var url = action+catChildAlias+'?'+queryString;

    var pageTitle = getPageTitleByQueryArray(queryArray);
    if(typeof(window.history.pushState) == 'function')
        window.history.pushState({"pageTitle":pageTitle}, pageTitle, url);        

    $('title').text(pageTitle);

    
    $.fn.yiiListView.update('post-list', {
        url: url
    });
    //    $('#post-list').yiiGridView('update', {
    //        data: $('#filter_form').serialize()+'&page=1'
    //    });
}

$('#toogle-filter').click(function(){
    $filters_encode = $.cookie('filters');
    $filters = $.parseJSON($filters_encode);
    if($filters == null) $filters = new Object;

    $('#search-form').slideToggle('fast', function(){
        var visible = $(this).is(":visible") ? 1 : 0;
        var cat_parent_alias = $('#filter_form').attr('cat_parent_alias');
        var cat_child_alias = $('#child_alias').val();
        if(cat_child_alias == '') cat_child_alias = 'all';
        $filters[cat_parent_alias][cat_child_alias]['visible'] = visible;
        $.cookie('filters', JSON.stringify($filters), {path: '/'});

        if(visible == 1){
            $('#toogle-filter i').removeClass('fa-search-plus').addClass('fa-search-minus');
        }else{
            $('#toogle-filter i').removeClass('fa-search-minus').addClass('fa-search-plus');
        }
    });

    return false;
});


$("#thanh-pho").change(function(){
    $("#quan").html('<option value="">Tất cả</option>');

    var city_alias = $(this).val();

    if(city_alias != ''){
        $.each($cityData[city_alias]['districts'], function(key, value){
            $("#quan").append('<option value="'+value.alias+'">'+value.name+'</option>');
        });
        $('#is_all_city_block').fadeIn();  
    }else{
        $('#is_all_city_block').fadeOut(function(){
            $('#toan-quoc').attr('checked', false);
        });
    }
    ajaxFormPost();
});

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    //e.target // activated tab
    //e.relatedTarget // previous tab
    $('#sap-xep').val($(e.target).attr('rel'));
    ajaxFormPost();
});

$('#filter_form').submit(function(e){
    e.preventDefault();
    ajaxFormPost();
})


$('#child_alias, #quan, #loai-tin, #tinh-trang, #dien-tich-su-dung, #dien-tich-mat-bang, #gia-tu, #gia-den, #trang-thai, #toan-quoc, #co-anh').change(function(){
    ajaxFormPost();
});




$('#child_alias').change(function(){
    if($(this).val() != ''){
        $('#panel-cats').slideUp();
        $('#cat_child_name').text($('#child_alias option:selected').text());
    }else{
        $('#panel-cats').slideDown();
        $('#cat_child_name').text('');
    }
});


var keyword = '';
$('#tim-kiem').on('focus', function(){
    keyword = $(this).val().trim();
});


var timer;
$('#tim-kiem').on('keyup', function(){
    var keyword_current = $(this).val().trim();
    clearTimeout(timer);
    timer = setTimeout(function(){
        if(keyword_current != keyword){
            ajaxFormPost();
        }   
        }, 600);
});
